package cn.tianya.irock.core;


import java.util.HashMap;
import java.util.Map;

import cn.tianya.irock.cache.ICache;
import cn.tianya.irock.security.GenericPrincipal;

import freemarker.template.Configuration;

public class HttpContext {
	private static ThreadLocal<HttpContext> contexts = new ThreadLocal<HttpContext>();
	private HttpRequest request;
	private HttpResponse response;
	private GenericPrincipal user;
	private Map<String, Object> items;
	private boolean isCustomContent;

	public HttpContext(HttpRequest request, HttpResponse response) {
		this.setRequest(request);
		this.setResponse(response);
		this.items = new HashMap<String, Object>();
		this.isCustomContent = false;

		HttpContext.setContext(this);
	}
	
	public boolean isCustomContent() {
		return isCustomContent;
	}

	public void setCustomContent(boolean isCustomContent) {
		this.isCustomContent = isCustomContent;
	}
		
	void setRequest(HttpRequest request) {
		this.request = request;
	}
	public HttpRequest request() {
		return this.request;
	}
	
	void setResponse(HttpResponse response) {
		this.response = response;
	}
	public HttpResponse response() {
		return this.response;
	}
	
	public void setItem(String key, Object value) {
		if (!this.items.containsKey(key)) {
			this.items.put(key, value);
		}
	}
	public Object getItem(String key) {
		return this.items.get(key);
	}
	
	public void removeItem(String key) {
		this.items.remove(key);
	}
	
	public String getUsername() {
		return this.user.getIdentity().getName();
	}
	
	public GenericPrincipal getUser() {
		return user;
	}

	public void setUser(GenericPrincipal user) {
		this.user = user;
	}

	public ICache cache() {
		return HttpRuntime.cache();
	}
	
	public Configuration getConfiguration() {
		return (Configuration)this.cache().get("freemarker_configuration");
	}
	
	protected static void setContext(HttpContext context) {
		contexts.set(context);
	}
	
	public static HttpContext current() {
		return contexts.get();
	}
	
	public static String getApplicationUrl() {
		return getApplicationUrl(HttpContext.current());
	}
	
	public static String getApplicationUrl(HttpContext context) {
		if (context == null)
			return "";
		
		String seterName = context.request.getServerName();
		String applicationPath = context.request.getContextPath();

		return seterName + applicationPath;
	}
	
	public static String getSiteUrl() {
		return getSiteUrl(HttpContext.current());
	}
	
	public static String getSiteUrl(HttpContext context) {
		return getApplicationUrl() + "/" + context.request.getSite();
	}
}
